<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备序列号(SN)" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入设备序列号(SN)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网络MAC地址" prop="mac">
        <el-input
          v-model="queryParams.mac"
          placeholder="请输入网络MAC地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属服务商" prop="agentName">
        <el-select
          v-model="queryParams.agentId"
          placeholder="选择服务商账号"
          filterable
          style="width: 190px"
          remote
        >
          <el-option
            v-for="item in agentOptions"
            :key="item.id"
            :label="item.agentName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="是否包含下级代理商"
        prop="agentName"
        v-if="!onlyShowSn"
      >
        <el-radio-group v-model="queryParams.isJunior">
          <el-radio value="1" size="large">是</el-radio>
          <el-radio value="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="外网IP地址" prop="outIp">
        <el-input
          v-model="queryParams.outIp"
          placeholder="请输入外网IP地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内网IP地址" prop="inIp">
        <el-input
          v-model="queryParams.inIp"
          placeholder="请输入内网IP地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否开启IPv6: " prop="ipv6Start">
        <el-select
          v-model="queryParams.ipv6Start"
          placeholder="请选择"
          clearable
          @change="handleQuery"
          style="width: 120px"
        >
          <el-option label="全部 " :value="''" />
          <el-option label="关闭" :value="0" />
          <el-option label="打开" :value="1" />
          <el-option label="未知" :value="2" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="是否开启UPNP:" prop="upnpStart">
        <el-select
          v-model="queryParams.upnpStart"
          placeholder="请选择"
          clearable
          @change="handleQuery"
          style="width: 120px"
        >
          <el-option label="全部 " :value="''" />
          <el-option label="关闭" :value="0" />
          <el-option label="打开" :value="1" />
          <el-option label="未知" :value="2" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="设备在线状态:" prop="onlineStatus">
        <el-select
          v-model="queryParams.onlineStatus"
          placeholder="请选择"
          clearable
          @change="handleQuery"
          style="width: 120px"
        >
          <el-option label="全部 " :value="''" />
          <el-option label="离线" :value="0" />
          <el-option label="在线" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="CDN在线状态:" prop="cdnOnline">
        <el-select
          v-model="queryParams.cdnOnline"
          placeholder="请选择"
          clearable
          @change="handleQuery"
          style="width: 120px"
        >
          <el-option label="全部 " :value="''" />
          <el-option label="离线" :value="0" />
          <el-option label="在线" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态:" prop="bindStatus">
        <el-select
          v-model="queryParams.bindStatus"
          placeholder="请选择"
          clearable
          @change="handleQuery"
          style="width: 120px"
        >
          <el-option label="全部 " :value="''" />
          <el-option label="未绑定" :value="0" />
          <el-option label="已绑定" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="省份:" prop="provinceCode">
        <el-select
          v-model="queryParams.provinceCode"
          placeholder="请选择省份"
          clearable
          @change="handleProvinceChange"
          :loading="districtLoading"
          style="width: 150px"
        >
          <el-option
            v-for="province in provinceOptions"
            :key="province.value"
            :label="province.label"
            :value="province.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="城市:" prop="cityCode">
        <el-select
          v-model="queryParams.cityCode"
          placeholder="请选择城市"
          clearable
          @change="handleCityChange"
          :disabled="!queryParams.provinceCode"
          :loading="cityLoading"
          style="width: 150px"
        >
          <el-option
            v-for="city in cityOptions"
            :key="city.value"
            :label="city.label"
            :value="city.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="区县:" prop="districtCode">
        <el-select
          v-model="queryParams.districtCode"
          placeholder="请选择区县"
          clearable
          @change="handleDistrictChange"
          :disabled="!queryParams.cityCode"
          :loading="districtDetailLoading"
          style="width: 150px"
        >
          <el-option
            v-for="district in districtOptions"
            :key="district.value"
            :label="district.label"
            :value="district.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="运营商:" prop="ispName">
        <el-select
          v-model="queryParams.ispName"
          placeholder="请选择运营商"
          clearable
          @change="handleQuery"
          style="width: 150px"
        >
          <el-option
            v-for="dict in operator_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['deviceBox:boxinfo:export']"
          >导出</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['deviceBox:boxinfo:add']"
          >批量下发插件</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['deviceBox:boxinfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['deviceBox:boxinfo:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['deviceBox:boxinfo:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="boxinfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="代理商"
        align="center"
        prop="agentName"
        width="200"
        v-if="columns[22].visible"
      />
      <el-table-column
        label="设备序列号(SN)"
        align="center"
        prop="sn"
        width="200"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="网络MAC地址"
        align="center"
        prop="mac"
        width="200"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="压测"
        align="center"
        prop="netPressResult"
        width="100"
        v-if="columns[20].visible"
      />
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        width="100"
        v-if="columns[21].visible"
      />
      <el-table-column
        label="设备在线状态:"
        align="center"
        width="120"
        prop="onlineStatus"
        v-if="columns[7].visible"
      >
        <template #default="scope">
          <el-tag
            :type="
              scope.row.onlineStatus === 1
                ? 'success'
                : scope.row.onlineStatus === 0
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.onlineStatus === 1
                ? "在线"
                : scope.row.onlineStatus === 0
                ? "离线"
                : "未知"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="CDN在线状态:"
        align="center"
        prop="cdnOnline"
        width="120"
        v-if="columns[8].visible"
      >
        <template #default="scope">
          <el-tag
            :type="
              scope.row.cdnOnline === 1
                ? 'success'
                : scope.row.cdnOnline === 0
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.cdnOnline === 1
                ? "在线"
                : scope.row.cdnOnline === 0
                ? "离线"
                : "未知"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="插件名称"
        align="center"
        prop="cloudName"
        width="100"
        v-if="columns[18].visible"
      />
      <el-table-column
        label="运营商"
        align="center"
        width="100"
        prop="ispName"
        v-if="columns[15].visible"
      />

      <el-table-column
        label="外网IP地址"
        align="center"
        prop="outIp"
        width="130"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="内网IP地址"
        align="center"
        prop="inIp"
        width="130"
        v-if="columns[3].visible"
      />

      <el-table-column
        label="是否开启IPv6"
        align="center"
        prop="ipv6Start"
        width="120"
        v-if="columns[4].visible"
      >
        <template #default="scope">
          <el-tag
            :type="
              scope.row.ipv6Start === 1
                ? 'success'
                : scope.row.ipv6Start === 0
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.ipv6Start === 1
                ? "开启"
                : scope.row.ipv6Start === 0
                ? "关闭"
                : "未知"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="是否开启UPNP"
        align="center"
        prop="upnpStart"
        width="120"
        v-if="columns[5].visible"
      >
        <template #default="scope">
          <el-tag
            :type="
              scope.row.upnpStart === 1
                ? 'success'
                : scope.row.upnpStart === 0
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.upnpStart === 1
                ? "开启"
                : scope.row.upnpStart === 0
                ? "关闭"
                : "未知"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="网络类型"
        align="center"
        prop="natType"
        width="120"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="绑定状态"
        align="center"
        prop="bindStatus"
        width="100"
        v-if="columns[9].visible"
      >
        <template #default="scope">
          <el-tag
            :type="
              scope.row.bindStatus === 1
                ? 'success'
                : scope.row.bindStatus === 0
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.bindStatus === 1
                ? "已绑定"
                : scope.row.bindStatus === 0
                ? "未绑定"
                : "未知"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="运行版本"
        align="center"
        prop="runVersion"
        width="100"
        v-if="columns[17].visible"
      />
      <el-table-column
        label="省份"
        align="center"
        width="100"
        prop="provinceName"
        v-if="columns[11].visible"
      />
      <el-table-column
        label="城市"
        align="center"
        width="100"
        prop="cityName"
        v-if="columns[12].visible"
      />
      <el-table-column
        label="区县"
        width="100"
        align="center"
        prop="regionName"
        v-if="columns[13].visible"
      />
      <el-table-column
        label="详细地址"
        align="center"
        prop="addressDetail"
        width="200"
        v-if="columns[14].visible"
        show-overflow-tooltip
      />

      <el-table-column
        label="插件运行状态:"
        align="center"
        width="120"
        prop="cdnRunStatus"
        v-if="columns[19].visible"
      >
        <template #default="scope">
          <el-tag
            :type="
              scope.row.cdnRunStatus === 1
                ? 'success'
                : scope.row.cdnRunStatus === 0
                ? 'danger'
                : scope.row.cdnRunStatus === 2
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.cdnRunStatus === 1
                ? "运行中"
                : scope.row.cdnRunStatus === 2
                ? "已停止"
                : scope.row.cdnRunStatus === 3
                ? "已卸载"
                : "未知"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="设备绑定时间"
        align="center"
        width="160"
        prop="bindTime"
        v-if="columns[16].visible"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="160"
        v-if="columns[10].visible"
      />

      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="deviceInfo(scope.row)"
            >详情</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['deviceBox:boxinfo:edit']"
            >修改</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['deviceBox:boxinfo:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer v-model="infoDrawer" :direction="'rtl'" size="90%">
      <template #header>
        <span style="font-size: 28px; font-weight: bold">设备详情</span>
      </template>
      <div class="drawer-content-optimized">
        <h3 style="margin-bottom: 12px">盒子信息</h3>
        <div
          style="margin-bottom: 12px; display: flex; flex-wrap: wrap; gap: 8px"
        >
          <el-button type="primary" size="small" @click="refreshBtn">
            刷新
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="confirmAndSendDeviceCommand('reboot_box')"
          >
            重启设备
          </el-button>
          <el-button type="success" size="small" @click="refreshPluginInfo">
            刷新插件信息
          </el-button>
          <el-button type="info" size="small"> 远程协助信息 </el-button>
          <el-button type="info" size="small"> 远程连接 </el-button>
          <el-button type="info" size="small"> 远程连接(服务) </el-button>
          <el-button
            type="success"
            size="small"
            @click="openShellCmdDialog('send_shell')"
          >
            下发Shell命令
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="openShellCmdDialog('send_shell_service')"
          >
            下发Shell命令(服务)
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="confirmAndSendDeviceCommand('send_shell_quick')"
          >
            快捷指令
          </el-button>
          <el-button type="danger" size="small" @click="openDisableBoxDialog">
            禁止使用盒子
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="confirmAndSendDeviceCommand('skip_protocol')"
          >
            跳过用户协议
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="confirmAndSendDeviceCommand('reset_pwd')"
          >
            重置模式密码
          </el-button>
          <el-button type="primary" size="small" @click="editTags">
            修改标签
          </el-button>
        </div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="盒子ID">{{
            deviceDetail.id
          }}</el-descriptions-item>
          <el-descriptions-item label="设备序列号(SN)">{{
            deviceDetail.sn || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="网络MAC地址">{{
            deviceDetail.mac || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="CDN名称">{{
            deviceDetail.cdnName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="CDN在线状态">{{
            deviceDetail.cdnOnline === 1
              ? "在线"
              : deviceDetail.cdnOnline === 0
              ? "离线"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{
            deviceDetail.createBy || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            deviceDetail.createTime || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="设备在线状态">{{
            deviceDetail.onlineStatus === 1
              ? "在线"
              : deviceDetail.onlineStatus === 0
              ? "离线"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="内网IP地址">{{
            deviceDetail.inIp || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="是否开启IPv6">{{
            deviceDetail.ipv6Start === 1
              ? "打开"
              : deviceDetail.ipv6Start === 0
              ? "关闭"
              : deviceDetail.ipv6Start === 2
              ? "未知"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="网络类型">{{
            deviceDetail.natType || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="外网IP地址">{{
            deviceDetail.outIp || "-"
          }}</el-descriptions-item>

          <el-descriptions-item label="云商名称">{{
            deviceDetail.cloudName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{
            deviceDetail.remark || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="更新者">{{
            deviceDetail.updateBy || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{
            deviceDetail.updateTime || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="是否开启UPNP">{{
            deviceDetail.upnpStart === 1
              ? "打开"
              : deviceDetail.upnpStart === 0
              ? "关闭"
              : deviceDetail.upnpStart === 2
              ? "未知"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="压测">{{
            deviceDetail.netPressResult || "0"
          }}</el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <h3 style="margin-bottom: 12px">PCDN信息</h3>
        <div
          style="margin-bottom: 12px; display: flex; flex-wrap: wrap; gap: 8px"
        >
          <el-button type="primary" size="small"> 本机收益 </el-button>
          <el-button type="success" size="small"> 刷新盒子收益 </el-button>
          <el-button type="info" size="small" @click="handlePressTest">
            压测
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="openPluginSelectDialog('send_plugin')"
          >
            下发插件
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="confirmAndSendDeviceCommand('stop_plugin')"
          >
            停止插件
          </el-button>
          <el-button
            type="success"
            size="small"
            @click="confirmAndSendDeviceCommand('start_plugin')"
          >
            启动插件
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="confirmAndSendDeviceCommand('clear_running_plugin')"
          >
            卸载插件
          </el-button>
          <!-- <el-button
            type="warning"
            size="small"
            @click="confirmAndSendDeviceCommand('clear_stop_plugin')"
          >
            清空待停止插件
          </el-button> -->
          <el-button type="primary" size="small">
            重新提交小Q盒子节点
          </el-button>
        </div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="插件在线状态">{{
            deviceDetail.cdnOnline === 1
              ? "在线"
              : deviceDetail.cdnOnline === 0
              ? "离线"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="运行中的插件">
            {{
              deviceDetail.cdnOnline === 1 ? deviceDetail.cdnName || "-" : "-"
            }}</el-descriptions-item
          >
          <el-descriptions-item label="待运行的插件">{{
            deviceDetail.waitRunPlugin || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="待停止的插件">{{
            deviceDetail.waitStopPlugin || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="插件部署整体状态">{{
            deviceDetail.cdnOnline === 1
              ? "服务中"
              : deviceDetail.cdnOnline === 0
              ? "-"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="插件部署失败原因">{{
            deviceDetail.pluginDeployFailReason || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="插件是否等待更新">{{
            deviceDetail.pluginWaitUpdate === 1
              ? "是"
              : deviceDetail.pluginWaitUpdate === 0
              ? "否"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="公网IP">{{
            deviceDetail.outIp || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="UPNP开关状态">{{
            deviceDetail.upnpStart === 1
              ? "开"
              : deviceDetail.upnpStart === 0
              ? "关"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="IPV6开关状态">{{
            deviceDetail.ipv6Start === 1
              ? "开"
              : deviceDetail.ipv6Start === 0
              ? "关"
              : "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="TCP NAT类型">{{
            deviceDetail.natType || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="UDP NAT类型">{{
            deviceDetail.udpNatType || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="省份">{{
            deviceDetail.provinceName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="城市">{{
            deviceDetail.city || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="运营商">{{
            deviceDetail.ispName || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="测速带宽">{{
            deviceDetail.speedTest || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="实际上传">{{
            deviceDetail.realUpload || "-"
          }}</el-descriptions-item>
          <el-descriptions-item
            v-if="deviceDetail.cdnName == '小w'"
            label="小W ID"
            >{{ deviceDetail.sn || "-" }}</el-descriptions-item
          >
          <el-descriptions-item
            v-else-if="deviceDetail.cdnName == '小q'"
            label="小Q ID"
            >{{ deviceDetail.sn || "-" }}</el-descriptions-item
          >
          <el-descriptions-item
            v-else-if="deviceDetail.cdnName == '小p'"
            label="小P ID"
            >{{ deviceDetail.sn || "-" }}</el-descriptions-item
          >

          <el-descriptions-item
            label="小W 业务"
            v-if="deviceDetail.cdnName == '小w'"
          >
            {{ deviceDetail.bizName || "-" }}
          </el-descriptions-item>
          <el-descriptions-item
            label="小Q 业务"
            v-else-if="deviceDetail.cdnName == '小q'"
          >
            {{ "-" }}
          </el-descriptions-item>
          <el-descriptions-item
            label="小P 业务"
            v-else-if="deviceDetail.cdnName == '小p'"
          >
            {{ "-" }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider />
        <h3 style="margin: 18px 0 12px 0">当前设备应用列表</h3>
        <div style="margin-bottom: 12px">
          <el-button type="primary" size="small" @click="openSelectAppDialog">
            选择下发安装应用
          </el-button>
          <!-- <el-button type="success" size="small" @click="openIssueAppDialog">
            新建应用下发
          </el-button> -->
          <el-button
            type="info"
            size="small"
            @click="confirmAndSendDeviceCommand('update_desktop')"
            >通知桌面更新配置</el-button
          >
        </div>
        <el-table :data="deviceDetail.appList || []" border style="width: 100%">
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button
                class="app-action-btn"
                type="danger"
                size="small"
                @click="uninstallApp(scope.row)"
              >
                卸载
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="应用图标" align="center" width="80">
            <template #default="scope">
              <el-image
                v-if="scope.row.icon"
                :src="scope.row.icon"
                style="width: 40px; height: 40px"
                fit="cover"
                :preview-src-list="[scope.row.icon]"
              />
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="应用名称" prop="name" align="center" />
          <el-table-column label="包名" prop="packageName" align="center" />
          <el-table-column label="版本名称" prop="versionName" align="center" />
          <el-table-column label="版本号" prop="versionCode" align="center" />
          <el-table-column label="应用大小" align="center" width="100">
            <template #default="scope">
              {{ formatFileSize(scope.row.size) }}
            </template>
          </el-table-column>
          <el-table-column label="安装状态" align="center" width="100">
            <template #default="scope">
              <el-tag
                :type="getInstallStatusType(scope.row.installStatus)"
                size="small"
              >
                {{ getInstallStatusText(scope.row.installStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="应用类型" align="center" width="100">
            <template #default="scope">
              <el-tag :type="getAppTypeTagType(scope.row.type)" size="small">
                {{ getAppTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="安装时间"
            prop="installTime"
            align="center"
            width="160"
          />
        </el-table>
        <el-divider />
        <h3 style="margin: 18px 0 12px 0">设备数据</h3>
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-click="handleClick"
        >
          <el-tab-pane label="收益" name="first">
            <IncomeTrendPanel
              v-if="activeName === 'first' && infoDrawer"
              :formDrawer="deviceDetail"
              :activeName="activeName"
            />
          </el-tab-pane>
          <el-tab-pane label="带宽" name="second">
            <BandwidthTrendPanel
              v-if="activeName === 'second' && infoDrawer"
              :formDrawer="deviceDetail"
              :activeName="activeName"
            />
          </el-tab-pane>
          <el-tab-pane label="网络信息" name="fourth">
            <NetworkInfoPanel
              v-if="activeName === 'fourth' && infoDrawer"
              :formDrawer="deviceDetail"
              :activeName="activeName"
              @getFetchDeviceDetail="getFetchDeviceDetail"
            />
          </el-tab-pane>
          <el-tab-pane label="硬件信息" name="fifth">
            <HardwareInfoPanel
              v-if="activeName === 'fifth' && infoDrawer"
              :formDrawer="deviceDetail"
              :activeName="activeName"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>

    <!-- 添加或修改盒子信息对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :width="dialogWidth"
      append-to-body
    >
      <el-form ref="boxinfoRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <!-- <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="设备序列号(SN)" prop="sn">
              <el-input v-model="form.sn" placeholder="请输入设备序列号(SN)" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="网络MAC地址" prop="mac">
              <el-input v-model="form.mac" placeholder="请输入网络MAC地址" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="外网IP地址" prop="outIp">
              <el-input v-model="form.outIp" placeholder="请输入外网IP地址" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="内网IP地址" prop="inIp">
              <el-input v-model="form.inIp" placeholder="请输入内网IP地址" />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="是否开启IPv6:" prop="ipv6Start">
              <el-input
                v-model="form.ipv6Start"
                placeholder=" 0-关闭, 1-打开, 2-未知"
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="是否开启UPNP:" prop="upnpStart">
              <el-input
                v-model="form.upnpStart"
                placeholder=" 0-关闭, 1-打开, 2-未知"
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="设备在线状态:" prop="onlineStatus">
              <el-input
                v-model="form.onlineStatus"
                placeholder="0-离线, 1-在线"
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="CDN在线状态:" prop="cdnOnline">
              <el-input v-model="form.cdnOnline" placeholder="0-离线, 1-在线" />
            </el-form-item>
          </el-col> -->

          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新建应用下发弹窗 -->
    <el-dialog
      v-model="issueAppDialogVisible"
      title="新建应用下发"
      width="90%"
      :z-index="300111"
      append-to-body
    >
      <el-form :model="issueAppForm" label-width="110px">
        <el-form-item label="APK文件上传">
          <el-upload
            class="apk-uploader"
            action="#"
            :show-file-list="false"
            :http-request="customIssueAppApkUploadRequest"
            accept=".apk"
          >
            <el-button type="primary">上传APK</el-button>
          </el-upload>
          <div
            v-if="issueAppForm.url"
            style="margin-top: 8px; color: #666; font-size: 13px"
          >
            已上传: {{ issueAppForm.url }}
          </div>
        </el-form-item>
        <el-form-item label="选择栏目" prop="columnId">
          <el-select
            v-model="issueAppForm.columnId"
            placeholder="请选择栏目"
            :z-index="30011111"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in columnList"
              :z-index="30011111"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用名称">
          <el-input v-model="issueAppForm.name" />
        </el-form-item>
        <el-form-item label="包名">
          <el-input v-model="issueAppForm.packageName" />
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="issueAppForm.versionCode" />
        </el-form-item>
        <el-form-item label="版本名称">
          <el-input v-model="issueAppForm.versionName" />
        </el-form-item>
        <el-form-item label="应用图标路径">
          <el-input v-model="issueAppForm.icon" />
        </el-form-item>
        <el-form-item label="APK文件路径">
          <el-input v-model="issueAppForm.url" readonly />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="issueAppDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitIssueApp">确定</el-button>
      </template>
    </el-dialog>

    <!-- 选择下发安装应用弹窗 -->
    <el-dialog
      v-model="selectAppDialogVisible"
      title="选择下发安装应用"
      width="500px"
      :z-index="300111"
      append-to-body
    >
      <el-form>
        <el-form-item label="栏目">
          <el-select
            v-model="columnIdAAA"
            placeholder="请选择"
            clearable
            popper-class="app-select-dropdown"
            style="width: 100%"
            @change="fetchSelectableAppList"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in columnList"
              :key="item.value || index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="应用" prop="selectedAppId">
          <el-select
            v-model="selectedAppId"
            placeholder="请先选择栏目"
            filterable
            :disabled="!columnIdAAA"
            :loading="selectAppLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in selectableAppList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="selectAppDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="issueSelectedAppHandler"
          :loading="selectAppLoading"
          >确定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog
      v-model="pluginSelectDialogVisible"
      title="选择插件"
      width="400px"
      append-to-body
    >
      <el-form>
        <el-form-item label="插件">
          <el-select
            v-model="selectedPluginId"
            placeholder="请选择插件"
            style="width: 100%"
          >
            <el-option
              v-for="item in pluginList"
              :key="item.providerId"
              :label="item.cloudName"
              :value="item.providerId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pluginSelectDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            () =>
              confirmAndSendDeviceCommand(
                pluginCmdValue,
                pluginList.find((item) => item.providerId === selectedPluginId)
              )
          "
          >确定</el-button
        >
      </template>
    </el-dialog>
    <el-dialog
      v-model="pluginSelectDialogVisible22"
      title="选择插件"
      width="400px"
      append-to-body
    >
      <el-form>
        <el-form-item label="插件">
          <el-select
            v-model="selectedPluginId22"
            placeholder="请选择插件"
            style="width: 100%"
          >
            <el-option label="无" value="''" key="''" />
            <el-option
              v-for="item in pluginList"
              :key="item.providerId"
              :label="item.cloudName"
              :value="item.providerId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pluginSelectDialogVisible22 = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            () =>
              confirmAndSendDeviceCommand222(
                pluginList.find(
                  (item) => item.providerId === selectedPluginId22
                )
              )
          "
          >确定</el-button
        >
      </template>
    </el-dialog>

    <el-dialog
      v-model="shellCmdDialogVisible"
      :title="
        shellCmdType === 'send_shell' ? '下发Shell命令' : '下发Shell命令(服务)'
      "
      width="500px"
      center
      append-to-body
    >
      <el-form>
        <el-form-item label="Shell命令">
          <el-input
            v-model="shellCmdInput"
            type="textarea"
            :rows="6"
            placeholder="请输入Shell命令"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shellCmdDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="
            () => confirmAndSendDeviceCommand(shellCmdType, shellCmdInput)
          "
          >确定</el-button
        >
      </template>
    </el-dialog>

    <!-- 禁止使用盒子弹窗 -->
    <el-dialog
      v-model="disableBoxDialogVisible"
      title="禁止使用盒子"
      width="400px"
      append-to-body
    >
      <el-form>
        <el-form-item label="请选择原因">
          <el-select
            v-model="disableBoxReason"
            placeholder="请选择原因"
            style="width: 100%"
          >
            <el-option
              v-for="item in disableBoxReasonOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="disableBoxDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDisableBox">确定</el-button>
      </template>
    </el-dialog>

    <el-drawer
      v-model="openTags"
      title="设备标签设置"
      direction="rtl"
      :destroyOnClose="true"
      @close="closeTags"
    >
      <div class="device-tag-setting">
        <!-- 顶部须知 -->
        <div class="top-alert">
          <div class="header-tip">
            <b>须知：</b>
            <p>
              1、开启设备标签时，<span class="red"
                >需要关注当前业务是否支持此标签</span
              >，如业务不支持，强行开启标签会导致0跑！
            </p>
            <p>
              2、开启日间、晚间峰调度等标签，可能会导致利用率降低(10%~15%左右)，请谨慎开启。
            </p>
          </div>
        </div>

        <el-form label-width="100px" class="form" label-position="top">
          <el-form-item label="调度范围">
            <el-select
              v-model="scope"
              placeholder="不限范围"
              style="width: 100%"
              @change="handleScopeChange"
            >
              <el-option
                v-for="item in scopeAry"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="调度时段">
            <el-select
              ref="periodRef"
              v-model="period"
              placeholder="请选择"
              style="width: 100%"
              @change="handlePeriodChange"
            >
              <el-option
                v-for="item in periodAry"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="纯跑IPv6">
            <template #label>
              <span>纯跑IPv6</span>
            </template>
            <el-select
              v-model="ipv6"
              placeholder="请选择"
              style="width: 100%"
              @change="handleIpv6Change"
            >
              <el-option
                v-for="item in ipv6Ary"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="异网支付">
            <el-select
              v-model="pay"
              multiple
              placeholder="请选择"
              style="width: 340px"
              @change="handlePayChange()"
              @remove-tag="removePayTag"
            >
              <el-option
                v-for="item in payAry"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script setup name="Boxinfo">
import {
  listBoxinfo,
  getBoxinfo,
  delBoxinfo,
  addBoxinfo,
  updateBoxinfo,
  executeDeviceCmd,
  getDeviceAppList,
  getSelectableAppList,
  issueSelectedApp,
  uninstallDeviceApp,
  sendDeviceCommand,
  pressTest,
} from "@/api/deviceBox/boxinfo";
import {
  listAgent,
} from "@/api/pcdn/info";
import {
  listColumnInfo,
  issueAppInfo,
  uploadAppApk,
} from "@/api/deviceBox/column";
import { districtList as getDistrictList } from "@/api/agent/agent";
import IncomeTrendPanel from "../../producer/device/components/IncomeTrendPanel.vue";
import BandwidthTrendPanel from "../../producer/device/components/BandwidthTrendPanel.vue";
import NetworkInfoPanel from "../../producer/device/components/NetworkInfoPanel.vue";
import HardwareInfoPanel from "../../producer/device/components/HardwareInfoPanel.vue";
import { updateDeviceTag } from "@/api/producer/device";
import request from "@/utils/request";
function getPluginList() {
  return request({
    url: "/plugin/plugin/list",
    method: "get",
    params: { hasPage: false },
  });
}

const { proxy } = getCurrentInstance();

// 引入字典数据
const { operator_type } = proxy.useDict("operator_type");

const boxinfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const infoDrawer = ref(false);
const deviceDetail = ref({
  appList: [],
});

// 新建应用下发相关变量
const issueAppDialogVisible = ref(false);
const issueAppForm = reactive({
  columnId: "", // 用空字符串，保证和下拉选项类型一致
  name: "",
  packageName: "",
  versionCode: "",
  versionName: "",
  icon: "",
  url: "",
  mac: "",
});
const columnIdAAA = ref("");
// 选择下发安装应用弹窗相关变量
const selectAppDialogVisible = ref(false);
const selectableAppList = ref([]);
const selectedAppId = ref(""); // 用字符串，和 el-select 兼容
const selectAppLoading = ref(false);

// 插件选择弹窗相关变量
const pluginSelectDialogVisible = ref(false);
const pluginSelectDialogVisible22 = ref(false);
const pluginList = ref([]);
const selectedPluginId = ref("");
const selectedPluginId22 = ref("");
const pluginCmdValue = ref(""); // 临时存储cmdValue
const pluginCmdValue22 = ref(""); // 临时存储cmdValue

// 下发Shell命令弹窗相关变量
const shellCmdDialogVisible = ref(false);
const shellCmdInput = ref("");
const shellCmdType = ref("send_shell"); // send_shell: 下发Shell命令, send_shell_service: 下发Shell命令(服务)

// 禁止使用盒子弹窗相关变量
const disableBoxDialogVisible = ref(false);
const disableBoxReason = ref("");
const disableBoxReasonOptions = [
  "您的网络太慢啦~请联系安装人员排查!",
  "检测到网络貌似限速~请联系当地运营商处理!",
  "为保障您的使用体验，请将机顶盒直连光猫!",
  "系统正在升级，大概2-3分钟左右，请勿动!",
];

// 地区筛选相关变量
const provinceOptions = ref([]);
const cityOptions = ref([]);
const districtOptions = ref([]);
const districtLoading = ref(false);
const cityLoading = ref(false);
const districtDetailLoading = ref(false);

// 列显隐信息
const columns = ref([
  { key: 0, label: `设备序列号(SN)`, visible: true },
  { key: 1, label: `网络MAC地址`, visible: true },
  { key: 2, label: `外网IP地址`, visible: true },
  { key: 3, label: `内网IP地址`, visible: true },
  { key: 4, label: `是否开启IPv6: `, visible: true },
  { key: 5, label: `是否开启UPNP: `, visible: true },
  { key: 6, label: `网络类型`, visible: true },
  { key: 7, label: `设备在线状态:`, visible: true },
  { key: 8, label: `CDN在线状态: `, visible: true },
  { key: 9, label: `绑定状态`, visible: true },
  { key: 10, label: `更新时间`, visible: true },
  { key: 11, label: `省份`, visible: true },
  { key: 12, label: `城市`, visible: true },
  { key: 13, label: `区县`, visible: true },
  { key: 14, label: `详细地址`, visible: true },
  { key: 15, label: `运营商`, visible: true },
  { key: 16, label: `设备绑定时间`, visible: true },
  { key: 17, label: `运行版本`, visible: true },
  { key: 18, label: `插件名称`, visible: true },
  { key: 19, label: `插件运行状态`, visible: true },
  { key: 20, label: `压测`, visible: true },
  { key: 21, label: `备注`, visible: true },
  { key: 22, label: `代理商`, visible: true },
]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sn: null,
    mac: null,
    outIp: null,
    agentId: null,
    isJunior: "1",
    inIp: null,
    ipv6Start: null,
    upnpStart: null,
    natType: null,
    onlineStatus: null,
    cdnOnline: null,
    bindStatus: null,
    provinceName: null,
    cityName: null,
    regionName: null,
    addressDetail: null,
    ispName: null,
    provinceCode: null, // 省份编码
    cityCode: null, // 城市编码
    districtCode: null, // 区县编码
  },
  rules: {
    mac: [{ required: true, message: "网络MAC地址不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询盒子信息列表 */
function getList() {
  loading.value = true;
  listBoxinfo(queryParams.value).then((response) => {
    boxinfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取栏目列表 */
function getColumnList() {
  listColumnInfo({ hasPage: false })
    .then((response) => {
      const allColumns = response.rows || response.data || [];
      // 过滤掉状态为0的栏目（不显示的栏目）
      columnList.value = [];
      allColumns.forEach((item) => {
        columnList.value.push({
          value: String(item.id), // 强制转字符串
          label: String(item.columnName),
        });
      });
    })
    .catch((error) => {
      console.error("获取栏目列表失败:", error);
      columnList.value = [];
    });
}

/**
 * 获取地区列表
 * @param {number} level 1=省，2=市，3=区
 * @param {string} pcode 上级地区code
 * @returns {Promise<Array>} 地区列表
 */
async function fetchDistrictList(level, pcode = "") {
  try {
    console.log("获取地区列表参数:", { level, pcode });
    const response = await getDistrictList({ level, pcode });
    console.log("地区列表API返回:", response);

    // 根据代理商页面的实现，API返回结构是 { code: 200, data: [...] }
    if (response.code === 200) {
      const list = response.data || response.rows || [];
      console.log("处理后的地区数据:", list);

      return list.map((item) => ({
        value: item.code,
        label: item.name,
      }));
    } else {
      console.error("API返回错误:", response);
      return [];
    }
  } catch (error) {
    console.error("获取地区列表失败:", error);
    return [];
  }
}

/**
 * 加载省份数据
 */
async function loadProvinceOptions() {
  districtLoading.value = true;
  try {
    const provinces = await fetchDistrictList(1);
    provinceOptions.value = provinces;
    console.log("加载省份数据成功:", provinces);
  } catch (error) {
    console.error("加载省份数据失败:", error);
    provinceOptions.value = [];
  } finally {
    districtLoading.value = false;
  }
}

/**
 * 获取静态省份数据
 */
function getStaticProvinces() {
  return [
    { value: "110000", label: "北京" },
    { value: "120000", label: "天津" },
    { value: "130000", label: "河北" },
    { value: "140000", label: "山西" },
    { value: "150000", label: "内蒙古" },
    { value: "210000", label: "辽宁" },
    { value: "220000", label: "吉林" },
    { value: "230000", label: "黑龙江" },
    { value: "310000", label: "上海" },
    { value: "320000", label: "江苏" },
    { value: "330000", label: "浙江" },
    { value: "340000", label: "安徽" },
    { value: "350000", label: "福建" },
    { value: "360000", label: "江西" },
    { value: "370000", label: "山东" },
    { value: "410000", label: "河南" },
    { value: "420000", label: "湖北" },
    { value: "430000", label: "湖南" },
    { value: "440000", label: "广东" },
    { value: "450000", label: "广西" },
    { value: "460000", label: "海南" },
    { value: "500000", label: "重庆" },
    { value: "510000", label: "四川" },
    { value: "520000", label: "贵州" },
    { value: "530000", label: "云南" },
    { value: "540000", label: "西藏" },
    { value: "610000", label: "陕西" },
    { value: "620000", label: "甘肃" },
    { value: "630000", label: "青海" },
    { value: "640000", label: "宁夏" },
    { value: "650000", label: "新疆" },
    { value: "710000", label: "台湾" },
    { value: "810000", label: "香港" },
    { value: "820000", label: "澳门" },
  ];
}
const agentOptions = ref([]);
listAgent().then((response) => {
  agentOptions.value = response.rows;
});

/**
 * 省份选择变化处理
 */
async function handleProvinceChange(provinceCode) {
  // 清空市和区的选择
  queryParams.value.cityCode = null;
  queryParams.value.districtCode = null;
  cityOptions.value = [];
  districtOptions.value = [];

  if (provinceCode) {
    cityLoading.value = true;
    try {
      const cities = await fetchDistrictList(2, provinceCode);
      cityOptions.value = cities;
      console.log("加载城市数据成功:", cities);
    } catch (error) {
      console.error("加载城市数据失败:", error);
      cityOptions.value = [];
    } finally {
      cityLoading.value = false;
    }
  }
}

/**
 * 城市选择变化处理
 */
async function handleCityChange(cityCode) {
  // 清空区的选择
  queryParams.value.districtCode = null;
  districtOptions.value = [];

  if (cityCode) {
    districtDetailLoading.value = true;
    try {
      const districts = await fetchDistrictList(3, cityCode);
      districtOptions.value = districts;
      console.log("加载区县数据成功:", districts);
    } catch (error) {
      console.error("加载区县数据失败:", error);
      districtOptions.value = [];
    } finally {
      districtDetailLoading.value = false;
    }
  }
}

/**
 * 区县选择变化处理
 */
function handleDistrictChange(districtCode) {
  // 区县选择变化时不需要额外处理
  console.log("选择区县:", districtCode);
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    sn: null,
    mac: null,
    outIp: null,
    inIp: null,
    agentId: null,
    isJunior: "1",
    ipv6Start: null,
    upnpStart: null,
    natType: null,
    onlineStatus: null,
    cdnOnline: null,
    bindStatus: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("boxinfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  form.value = {
    pageNum: 1,
    pageSize: 10,
    sn: null,
    mac: null,
    outIp: null,
    agentId: null,
    isJunior: "1",
    inIp: null,
    ipv6Start: null,
    upnpStart: null,
    natType: null,
    onlineStatus: null,
    cdnOnline: null,
    bindStatus: null,
    provinceName: null,
    cityName: null,
    regionName: null,
    addressDetail: null,
    ispName: null,
    provinceCode: null,
    cityCode: null,
    districtCode: null,
  };
  proxy.resetForm("queryRef");
  handleQuery();
}
const idsMac = ref([]);
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  idsMac.value = selection.map((item) => item.mac);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  getPluginList().then((res) => {
    pluginList.value = res.rows || [];
    selectedPluginId22.value = "";
    pluginSelectDialogVisible22.value = true;
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getBoxinfo(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改备注";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["boxinfoRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBoxinfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBoxinfo(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除盒子信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delBoxinfo(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "deviceBox/boxinfo/export",
    {
      ...queryParams.value,
    },
    `boxinfo_${new Date().getTime()}.xlsx`
  );
}

getList();
getColumnList(); // 调用获取栏目列表的函数
loadProvinceOptions(); // 加载省份数据

/** 动态计算字段数 **/
const fieldCount = ref(0);

onMounted(() => {
  // 统计表单字段数量
  fieldCount.value = [
    "sn",
    "mac",
    "outIp",
    "agentId",
    "isJunior",
    "inIp",
    "ipv6Start",
    "upnpStart",
    "natType",
    "onlineStatus",
    "cdnOnline",
    "bindStatus",
    "remark",
  ].length;
});

const isTwoColumnForm = computed(() => fieldCount.value > 8);
const dialogWidth = computed(() => (isTwoColumnForm.value ? "60vw" : "500px"));

function deviceInfo(row) {
  getBoxinfo(row.id).then((response) => {
    deviceDetail.value = response.data;
    if (response.data.tagList) {
      try {
        response.data.tagList = JSON.parse(response.data.tagList);
        response.data.tagListname = response.data.tagList
          .map((item) => item.tagValue)
          .join(",");
      } catch (e) {
        console.error("Error parsing tagList:", e);
      }
    }
    // 获取设备应用列表
    if (response.data.mac) {
      getDeviceAppList(response.data.mac, response.data.id)
        .then((appResponse) => {
          deviceDetail.value.appList = appResponse.rows || [];
        })
        .catch((error) => {
          console.error("获取应用列表失败:", error);
          deviceDetail.value.appList = [];
        });
    }
  });
  infoDrawer.value = true;
}

function viewPhoto(url) {
  proxy.$modal.msgInfo("预览图片功能待实现");
}
function updateSuperPassword() {
  proxy.$modal.msgInfo("超密更新功能待实现");
}

// 执行盒子命令
function executeBoxCmd(cmdValue) {
  if (!deviceDetail.value.mac) {
    proxy.$modal.msgError("设备MAC地址不能为空");
    return;
  }
  if (cmdValue === 6 || cmdValue === 7) {
    shellCmdType.value = cmdValue;
    shellCmdInput.value = "";
    shellCmdDialogVisible.value = true;
    return;
  }
  const cmdData = {
    cmdType: "box_cmd",
    cmdValve: cmdValue,
    mac: deviceDetail.value.mac,
  };
  executeDeviceCmd(cmdData)
    .then((response) => {
      proxy.$modal.msgSuccess("命令执行成功");
    })
    .catch((error) => {
      proxy.$modal.msgError("命令执行失败：" + (error.message || "未知错误"));
    });
}
const columnList = ref([]);
// 新的下发指令功能
function sendNewDeviceCommand(cmd, data = null) {
  if (!deviceDetail.value.mac) {
    proxy.$modal.msgError("设备MAC地址不能为空");
    return;
  }

  // 调试信息
  console.log("发送指令参数:", { cmd, data, mac: deviceDetail.value.mac });

  const loading = proxy.$loading({
    lock: true,
    text: "指令发送中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 30011200,
  });

  sendDeviceCommand(cmd, data, deviceDetail.value.mac)
    .then((response) => {
      proxy.$modal.msgSuccess("指令发送成功");
      pluginSelectDialogVisible.value = false;
    })
    .catch((error) => {
      proxy.$modal.msgError("指令发送失败：" + (error.message || "未知错误"));
    })
    .finally(() => {
      loading.close();
    });
}
function confirmAndSendDeviceCommand222(data) {
  if (idsMac.value.length == 0) {
    proxy.$modal.msgError("请选择设备");
    return;
  }

  let c = idsMac.value.join(",");
  proxy.$modal
    .confirm("确定要批量下发插件吗？")
    .then(() => {
      const loading = proxy.$loading({
        lock: true,
        text: "指令发送中...",
        background: "rgba(0, 0, 0, 0.7)",
        zIndex: 30011200,
      });
      sendDeviceCommand("send_plugin", data, c)
        .then((response) => {
          proxy.$modal.msgSuccess("批量下发插件成功");
          pluginSelectDialogVisible22.value = false;
          getList();
        })
        .catch((error) => {
          proxy.$modal.msgError(
            "批量下发插件失败：" + (error.message || "未知错误")
          );
        })
        .finally(() => {
          loading.close();
        });
    })
    .catch(() => {});
}
function confirmAndSendDeviceCommand(cmd, data = null) {
  const cmdTextMap = {
    send_plugin: "确定要下发插件吗？",
    stop_plugin: "确定要停止插件吗？",
    clear_running_plugin: "确定要清空待运行插件吗？",
    clear_stop_plugin: "确定要清空待停止插件吗？",
    send_app: "确定要下发应用吗？",
    del_app: "确定要卸载该应用吗？",
    update_desktop: "确定要通知桌面更新配置吗？",
    reboot_box: "确定要重启设备吗？",
    send_shell: "确定要下发Shell命令吗？",
    send_shell_service: "确定要下发Shell命令(服务)吗？",
    send_shell_quick: "确定要下发快捷指令吗？",
    box_disable: "确定要禁止使用盒子吗？",
    skip_protocol: "确定要跳过用户协议吗？",
    reset_pwd: "确定要重置模式密码吗？",
  };
  const text = cmdTextMap[cmd] || "确定要执行该操作吗？";
  proxy.$modal
    .confirm(text)
    .then(() => {
      sendNewDeviceCommand(cmd, data);
    })
    .catch(() => {});
}

// 打开Shell命令弹窗
function openShellCmdDialog(cmdType) {
  shellCmdType.value = cmdType;
  shellCmdInput.value = "";
  shellCmdDialogVisible.value = true;
}

// 打开插件选择弹窗
function openPluginSelectDialog(cmdType) {
  pluginCmdValue.value = cmdType;
  getPluginList().then((res) => {
    pluginList.value = res.rows || [];
    selectedPluginId.value = "";
    pluginSelectDialogVisible.value = true;
  });
}

// 执行插件命令（保留原有功能）
function executePluginCmd(cmdValue) {
  if (!deviceDetail.value.mac) {
    proxy.$modal.msgError("设备MAC地址不能为空");
    return;
  }

  // 保留原有的命令逻辑（本机收益、刷新盒子收益、压测、重新提交小Q盒子节点）
  const cmdData = {
    cmdType: "plugin_cmd",
    cmdValve: cmdValue,
    mac: deviceDetail.value.mac,
  };
  executeDeviceCmd(cmdData)
    .then((response) => {
      proxy.$modal.msgSuccess("命令执行成功");
    })
    .catch((error) => {
      proxy.$modal.msgError("命令执行失败：" + (error.message || "未知错误"));
    });
}

function confirmPluginCmd() {
  if (!selectedPluginId.value) {
    proxy.$modal.msgError("请选择插件");
    return;
  }

  // 找到选中的插件对象
  const selectedPlugin = pluginList.value.find(
    (item) => item.providerId === selectedPluginId.value
  );
  if (!selectedPlugin) {
    proxy.$modal.msgError("未找到选中的插件");
    return;
  }

  // 调试信息
  console.log("插件选择参数:", {
    cmd: pluginCmdValue.value,
    data: selectedPlugin,
    mac: deviceDetail.value.mac,
  });

  sendNewDeviceCommand(pluginCmdValue.value, selectedPlugin);
  pluginSelectDialogVisible.value = false;
}

// 格式化文件大小
function formatFileSize(bytes) {
  if (!bytes || bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}

// 获取安装状态文本
function getInstallStatusText(status) {
  const statusMap = {
    1: "安装中",
    2: "安装成功",
    3: "安装失败",
    4: "卸载中",
    5: "卸载失败",
  };
  return statusMap[status] || "未知";
}

// 获取安装状态标签类型
function getInstallStatusType(status) {
  const typeMap = {
    1: "warning",
    2: "success",
    3: "danger",
    4: "warning",
    5: "danger",
  };
  return typeMap[status] || "info";
}

// 获取应用类型文本
function getAppTypeText(type) {
  const typeMap = {
    1: "栏目",
    2: "投屏",
    3: "文件",
    4: "测速",
  };
  return typeMap[type] || "未知";
}

// 获取应用类型标签类型
function getAppTypeTagType(type) {
  const typeMap = {
    1: "primary",
    2: "success",
    3: "warning",
    4: "info",
  };
  return typeMap[type] || "info";
}

// 安装应用
function installApp(app) {
  proxy.$modal.msgInfo("安装应用功能待实现: " + app.ptitle);
}

// 卸载应用
function uninstallApp(app) {
  proxy.$modal
    .confirm(`确定要卸载应用 "${app.name}" 吗？`)
    .then(() => {
      if (!app.id || !deviceDetail.value.mac) {
        proxy.$modal.msgError("应用ID或设备MAC地址缺失");
        return;
      }
      proxy.$loading({
        lock: true,
        text: "正在卸载应用...",
        background: "rgba(0,0,0,0.7)",
        zIndex: 30011200,
      });
      let appId = Number(app.id);
      uninstallDeviceApp(appId, deviceDetail.value.mac)
        .then(() => {
          proxy.$modal.msgSuccess("卸载应用成功");
          // 刷新应用列表
          getDeviceAppList(deviceDetail.value.mac, deviceDetail.value.id)
            .then((appResponse) => {
              deviceDetail.value.appList = appResponse.rows || [];
            })
            .catch(() => {
              deviceDetail.value.appList = [];
            });
        })
        .catch((err) => {
          proxy.$modal.msgError("卸载应用失败：" + (err.message || "未知错误"));
        })
        .finally(() => {
          proxy.$loading().close();
        });
    })
    .catch(() => {});
}

// 更新应用
function updateApp(app) {
  proxy.$modal.msgInfo("更新应用功能待实现: " + app.ptitle);
}

// 打开新建应用下发弹窗
function openIssueAppDialog() {
  // 重置表单
  Object.assign(issueAppForm, {
    columnId: "", // 用空字符串
    name: "",
    packageName: "",
    versionCode: "",
    versionName: "",
    icon: "",
    url: "",
    mac: deviceDetail.value.mac || "",
    isCommon: 0, // 重置为0
  });

  // 重新获取栏目列表，确保数据是最新的
  getColumnList();

  issueAppDialogVisible.value = true;
}

// 自定义APK上传请求
async function customIssueAppApkUploadRequest(option) {
  const loading = proxy.$loading({
    lock: true,
    text: "APK文件上传中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 30011200,
  });

  let formData = new FormData();
  formData.append("file", option.file);
  try {
    const res = await uploadAppApk(formData);

    if (res.apk) {
      issueAppForm.name = res.apk.name || "";
      issueAppForm.packageName = res.apk.packageName || "";
      issueAppForm.versionCode = res.apk.versionCode || "";
      issueAppForm.versionName = res.apk.versionName || "";
      issueAppForm.icon = res.apk.icon || "";
    }
    issueAppForm.url = res.url || "";
    option.onSuccess(res, option.file);
    proxy.$modal.msgSuccess("APK文件上传成功");
  } catch (e) {
    console.log(e);
    proxy.$modal.msgError("APK文件上传失败");
    option.onError();
  } finally {
    loading.close();
  }
}

// 提交应用下发
async function submitIssueApp() {
  if (!issueAppForm.columnId) {
    proxy.$modal.msgError("请选择栏目");
    return;
  }

  if (!issueAppForm.url) {
    proxy.$modal.msgError("请上传APK文件");
    return;
  }

  if (!issueAppForm.mac) {
    proxy.$modal.msgError("设备MAC地址不能为空");
    return;
  }

  const loading = proxy.$loading({
    lock: true,
    text: "应用下发中...",
    background: "rgba(0, 0, 0, 0.7)",
    zIndex: 30011200,
  });

  try {
    await issueAppInfo({
      ...issueAppForm,
      columnId: issueAppForm.columnId,
      id: deviceDetail.value.id,
    });
    proxy.$modal.msgSuccess("应用下发成功");
    issueAppDialogVisible.value = false;
    // 刷新设备应用列表
    if (deviceDetail.value.mac) {
      getDeviceAppList(deviceDetail.value.mac)
        .then((appResponse) => {
          deviceDetail.value.appList = appResponse.rows || [];
        })
        .catch((error) => {
          console.error("获取应用列表失败:", error);
          deviceDetail.value.appList = [];
        });
    }
  } catch (error) {
    proxy.$modal.msgError("应用下发失败：" + (error.message || "未知错误"));
  } finally {
    loading.close();
  }
}

// 获取可选应用列表
function fetchSelectableAppList() {
  selectAppLoading.value = true;
  selectableAppList.value = [];
  selectedAppId.value = "";
  console.log('selectedAppId',selectedAppId.value);
  getSelectableAppList(0, 1, columnIdAAA.value)
    .then((res) => {
      const rows = res.rows || res.data || [];
      selectableAppList.value = rows.map((item) => ({
        value: String(item.id),
        label: `${item.name || item.packageName || "未知"}（${
          item.versionName || ""
        }）`,
        raw: item,
      }));
    })
    .finally(() => {
      selectAppLoading.value = false;
    });
  
}

// 打开弹窗
function openSelectAppDialog() {
  selectedAppId.value = "";
  columnIdAAA.value = "";
  selectableAppList.value = [];
  // fetchSelectableAppList();
  selectAppDialogVisible.value = true;
}

// 下发应用
function issueSelectedAppHandler() {
  if (!selectedAppId.value) {
    proxy.$modal.msgError("请选择应用");
    return;
  }
  if (!deviceDetail.value.mac) {
    proxy.$modal.msgError("设备MAC地址不能为空");
    return;
  }
  selectAppLoading.value = true;
  issueSelectedApp(selectedAppId.value, deviceDetail.value.mac)
    .then(() => {
      proxy.$modal.msgSuccess("应用下发成功");
      selectAppDialogVisible.value = false;
      // 刷新应用列表
      if (deviceDetail.value.mac) {
        getDeviceAppList(deviceDetail.value.mac, deviceDetail.value.id)
          .then((appResponse) => {
            deviceDetail.value.appList = appResponse.rows || [];
          })
          .catch(() => {
            deviceDetail.value.appList = [];
          });
      }
    })
    .catch((err) => {
      proxy.$modal.msgError("应用下发失败：" + (err.message || "未知错误"));
    })
    .finally(() => {
      selectAppLoading.value = false;
    });
}

function submitShellCmd() {
  if (!shellCmdInput.value.trim()) {
    proxy.$modal.msgError("请输入Shell命令");
    return;
  }

  // 调试信息
  console.log("Shell命令参数:", {
    cmd: shellCmdType.value,
    data: shellCmdInput.value.trim(),
    mac: deviceDetail.value.mac,
  });

  sendNewDeviceCommand(shellCmdType.value, shellCmdInput.value.trim());
  shellCmdDialogVisible.value = false;
}

// 盒子压测
function handlePressTest() {
  proxy.$modal
    .confirm("确定要对该设备进行压测吗？")
    .then(() => {
      if (!deviceDetail.value.sn) {
        proxy.$modal.msgError("设备序列号(SN)不存在");
        return;
      }
      const loading = proxy.$loading({
        lock: true,
        text: "压测请求中...",
        background: "rgba(0, 0, 0, 0.7)",
        zIndex: 30011200,
      });
      pressTest(deviceDetail.value.sn)
        .then(() => {
          proxy.$modal.msgSuccess("压测请求已发送");
        })
        .catch((err) => {
          proxy.$modal.msgError("压测失败：" + (err.message || "未知错误"));
        })
        .finally(() => {
          loading.close();
        });
    })
    .catch(() => {});
}
function refreshBtn() {
  getBoxinfo(deviceDetail.value.id).then((response) => {
    proxy.$modal.msgSuccess("刷新成功");
    deviceDetail.value = response.data;
  });
}
function refreshPluginInfo() {
  proxy.$modal
    .confirm("确定刷新插件信息吗？")
    .then(() => {
      getBoxinfo(deviceDetail.value.id).then((response) => {
        proxy.$modal.msgSuccess("刷新成功");
        deviceDetail.value = response.data;
        // 获取设备应用列表
        if (response.data.mac) {
          getDeviceAppList(response.data.mac, response.data.id)
            .then((appResponse) => {
              deviceDetail.value.appList = appResponse.rows || [];
            })
            .catch((error) => {
              console.error("获取应用列表失败:", error);
              deviceDetail.value.appList = [];
            });
        }
      });
    })
    .catch(() => {});
}

function openDisableBoxDialog() {
  disableBoxReason.value = "";
  disableBoxDialogVisible.value = true;
}

function confirmDisableBox() {
  if (!disableBoxReason.value) {
    proxy.$modal.msgError("请选择原因");
    return;
  }
  disableBoxDialogVisible.value = false;
  // 传递原因作为参数
  confirmAndSendDeviceCommand("box_disable", disableBoxReason.value);
}

const openTags = ref(false);
const scope = ref({ label: "不限范围", value: 2 });
const period = ref({ label: "不限时段", value: "none_time" });
const ipv6 = ref({ label: "关闭", value: 2 });
const pay = ref([]);
const skipPayChange = ref(false);
const skipStr = ref(0);

const scopeAry = ref([
  { label: "不限范围", value: 2 },
  { label: "同省调度", value: "intra_provincial" },
]);
const periodAry = ref([
  { label: "不限时段", value: "none_time" },
  { label: "纯跑晚高峰", value: "evening_peak" },
  { label: "纯跑午晚高峰", value: "noon_peak" },
]);
const ipv6Ary = ref([
  { label: "关闭", value: 2 },
  { label: "开启", value: "internet_ipv6" },
]);
const payAry = ref([
  { label: "交付电信", value: "mix_isp_1" },
  { label: "交付联通", value: "mix_isp_2" },
  { label: "交付移动", value: "mix_isp_5" },
]);

const tagsParams = reactive({
  sn: null,
  tagName: null,
  tagStatus: null,
  tagValue: null,
});

function handleScopeChange() {
  if (scope.value.value == "2") {
    tagsParams.sn = deviceDetail.value.sn;
    tagsParams.tagName = "intra_provincial";
    tagsParams.tagStatus = scope.value.value;
    tagsParams.tagValue = "同省调度";
  } else {
    tagsParams.sn = deviceDetail.value.sn;
    tagsParams.tagName = scope.value.value;
    tagsParams.tagStatus = "1";
    tagsParams.tagValue = "同省调度";
  }

  updateDeviceTag(tagsParams).then((response) => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("操作成功");
      getFetchDeviceDetail();
    }
  });
}

function handlePeriodChange() {
  let oldValue = proxy.$refs.periodRef.modelValue;
  const newValue = period.value;
  if (typeof oldValue === "string") {
    oldValue = periodAry.value.find((item) => item.value === oldValue) || {
      value: oldValue,
      label: oldValue,
    };
  }

  const oldValueItem = periodAry.value.find(
    (item) => item.value === oldValue.value
  );
  const newValueItem = periodAry.value.find(
    (item) => item.value === newValue.value
  );

  if (oldValue.value === "none_time") {
    if (newValue.value !== "none_time") {
      addPeriodTag(newValueItem);
    }
    return;
  }

  if (newValue.value === "none_time") {
    deletePeriodTag(oldValueItem);
    return;
  }

  if (oldValue.value !== "none_time" && newValue.value !== "none_time") {
    deletePeriodTag(oldValueItem);
    if (
      typeof newValueItem !== "string" &&
      newValueItem.value !== "none_time"
    ) {
      setTimeout(() => addPeriodTag(newValueItem), 1000);
    }
  }
}

function addPeriodTag(periodItem) {
  nextTick(() => {
    tagsParams.sn = deviceDetail.value.sn;
    tagsParams.tagName = periodItem.value;
    tagsParams.tagStatus = "1";
    tagsParams.tagValue = periodItem.label;

    return updateDeviceTag(tagsParams).then((response) => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess("操作成功");
        getFetchDeviceDetail();
      }
    });
  });
}

function deletePeriodTag(periodItem) {
  nextTick(() => {
    tagsParams.sn = deviceDetail.value.sn;
    tagsParams.tagName = periodItem.value;
    tagsParams.tagStatus = "2";
    tagsParams.tagValue = periodItem.label;

    return updateDeviceTag(tagsParams).then((response) => {
      if (response.code === 200) {
        proxy.$modal.msgSuccess("操作成功");
        getFetchDeviceDetail();
      }
    });
  });
}

function handleIpv6Change() {
  if (ipv6.value.value == "2") {
    tagsParams.sn = deviceDetail.value.sn;
    tagsParams.tagName = "internet_ipv6";
    tagsParams.tagStatus = ipv6.value.value;
    tagsParams.tagValue = "ipv6纯跑";
  } else {
    tagsParams.sn = deviceDetail.value.sn;
    tagsParams.tagName = "internet_ipv6";
    tagsParams.tagStatus = "1";
    tagsParams.tagValue = "ipv6纯跑";
  }

  updateDeviceTag(tagsParams).then((response) => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("操作成功");
      getFetchDeviceDetail();
    }
  });
}

function handlePayChange(value, str) {
  nextTick(() => {
    if (skipStr.value == 0) {
      let newPay = null;
      if (pay.value.length > 0) {
        newPay = [pay.value[pay.value.length - 1]];

        let name = null;
        if (newPay == "mix_isp_1") {
          name = "交付电信";
        } else if (newPay == "mix_isp_2") {
          name = "交付联通";
        } else if (newPay == "mix_isp_5") {
          name = "交付移动";
        }

        tagsParams.sn = deviceDetail.value.sn;
        tagsParams.tagName = newPay[0];
        tagsParams.tagStatus = "1";
        tagsParams.tagValue = name;

        updateDeviceTag(tagsParams).then((response) => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("操作成功");
            getFetchDeviceDetail();
          }
        });
      }
    }
  });
}

function closeTags() {
  pay.value = [];
}

function removePayTag(oldvalue) {
  skipPayChange.value = true;
  skipStr.value += 1;
  if (typeof oldvalue === "string") {
    oldvalue = payAry.value.find((item) => item.value === oldvalue) || {
      value: oldvalue,
      label: oldvalue,
    };
  }
  let newValue = payAry.value.find((item) => item.value == oldvalue.value);

  let name = null;
  if (oldvalue == "mix_isp_1") {
    name = "交付电信";
  } else if (oldvalue == "mix_isp_2") {
    name = "交付联通";
  } else if (oldvalue == "mix_isp_5") {
    name = "交付移动";
  }
  tagsParams.sn = deviceDetail.value.sn;
  tagsParams.tagName = newValue.value;
  tagsParams.tagStatus = "2";
  tagsParams.tagValue = newValue.label;

  updateDeviceTag(tagsParams).then((response) => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("操作成功");
      skipStr.value = 0;
      getFetchDeviceDetail();
      nextTick(() => {
        skipPayChange.value = false;
      });
    }
  });
}

function editTags() {
  openTags.value = true;
  if (deviceDetail.value.tagList && deviceDetail.value.tagList.length > 0) {
    deviceDetail.value.tagList.forEach((item) => {
      scopeAry.value.forEach((item1) => {
        if (item1.label == item.tagValue) {
          Object.assign(scope, item1);
        }
      });
      periodAry.value.forEach((item1) => {
        if (item1.label == item.tagValue) {
          Object.assign(period, item1);
        }
      });
      ipv6Ary.value.forEach((item1) => {
        if (item.tagValue == "纯跑ipv6") {
          Object.assign(ipv6, item1);
        }
      });
      payAry.value.forEach((item1) => {
        if (
          item.tagValue &&
          item1.label &&
          item.tagValue.includes(item1.label)
        ) {
          pay.value.push(item1);
        }
      });
    });
  }
}

function getFetchDeviceDetail(id) {
  if (id) {
    getBoxinfo(id).then((response) => {
      if (response.data.tagList) {
        try {
          response.data.tagList = JSON.parse(response.data.tagList);
          response.data.tagListname = response.data.tagList
            .map((item) => item.tagValue)
            .join(",");
        } catch (e) {
          console.error("Error parsing tagList:", e);
        }
      }
      deviceDetail.value = response.data;
      infoDrawer.value = true;
    });
  } else {
    getBoxinfo(deviceDetail.value.id).then((response) => {
      if (response.data.tagList) {
        try {
          response.data.tagList = JSON.parse(response.data.tagList);
          response.data.tagListname = response.data.tagList
            .map((item) => item.tagValue)
            .join(",");
        } catch (e) {
          console.error("Error parsing tagList:", e);
        }
      }
      deviceDetail.value = response.data;
      infoDrawer.value = true;
    });
  }
}

const activeName = ref("first");

function handleClick(tab, event) {
  console.log("tab clicked:", tab, event);
}
</script>

<style scoped>
.drawer-content-optimized {
  font-size: 16px;
  line-height: 1.8;
  padding: 0 24px 24px 24px;
  background: #fafbfc;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.drawer-content-optimized h3 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 18px;
  margin-top: 24px;
}
.drawer-content-optimized .el-descriptions {
  font-size: 16px;
  line-height: 2.2;
  --el-descriptions-border-color: #e4e7ed;
  --el-descriptions-label-color: #888;
  --el-descriptions-content-color: #222;
  --el-descriptions-label-font-weight: 500;
  border-radius: 6px;
  background: #fff;
  margin-bottom: 18px;
}
.drawer-content-optimized .el-descriptions__label {
  color: #888;
  text-align: right;
  font-weight: 500;
  background: #f6f8fa;
  border-radius: 4px 0 0 4px;
}
.drawer-content-optimized .el-descriptions__content {
  color: #222;
  text-align: left;
  background: #fff;
  border-radius: 0 4px 4px 0;
}
.drawer-content-optimized .el-descriptions__cell {
  padding: 10px 16px;
}
.drawer-content-optimized .el-divider {
  margin: 28px 0;
}
.drawer-content-optimized .el-button {
  margin-right: 12px;
  margin-bottom: 10px;
  min-width: 96px;
  border-radius: 6px;
  font-weight: 500;
}
.drawer-content-optimized .el-table {
  font-size: 15px;
  line-height: 1.7;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
  margin-bottom: 8px;
}
.drawer-content-optimized .el-table th {
  background: #f6f8fa;
  font-weight: bold;
  color: #333;
  border-bottom: 1px solid #e4e7ed;
}
.drawer-content-optimized .el-table td {
  border-bottom: 1px solid #f0f0f0;
}
.drawer-content-optimized .el-table th,
.drawer-content-optimized .el-table td {
  padding: 12px 0;
}
.drawer-content-optimized .el-table__row:hover {
  background: #f0f6ff;
}
.app-action-btn {
  border-radius: 6px;
  font-weight: 500;
  padding: 4px 14px;
  min-width: 60px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
  transition: background 0.2s, color 0.2s;
}
.app-action-btn[type="danger"],
.app-action-btn.el-button--danger {
  background: #fff0f0;
  color: #d93026;
  border: 1px solid #ffd6d6;
}
.app-action-btn[type="danger"]:hover,
.app-action-btn.el-button--danger:hover {
  background: #ffd6d6;
  color: #b71c1c;
}

.app-action-btn[type="primary"],
.app-action-btn.el-button--primary {
  background: #f0f9ff;
  color: #1890ff;
  border: 1px solid #b3d8ff;
}

.app-action-btn[type="primary"]:hover,
.app-action-btn.el-button--primary:hover {
  background: #b3d8ff;
  color: #096dd9;
}

.app-action-btn[type="warning"],
.app-action-btn.el-button--warning {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.app-action-btn[type="warning"]:hover,
.app-action-btn.el-button--warning:hover {
  background: #ffd591;
  color: #d46b08;
}

.drawer-content-optimized .el-image {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.drawer-content-optimized .el-tag {
  border-radius: 4px;
  font-weight: 500;
}
.header-tip {
  background: #fffbe6;
  border: 1px solid #ffe58f;
  padding: 10px 15px;
}
.header-tip p {
  margin: 0;
  font-size: 12px;
  color: #333;
  line-height: 19px;
}
.header-tip b {
  font-weight: normal;
  color: #000;
  font-size: 13px;
  margin-bottom: 6px;
}
</style>

<style>
.el-select-dropdown,
.el-popper,
.el-select__popper {
  z-index: 30011111 !important;
}
.el-loading-mask {
  z-index: 30011200 !important;
}
.el-overlay-dialog {
  display: flex !important;
  align-items: center;
  justify-content: center;
}
</style>

